package response

import (
	"encoding/json"
	"github.com/prometheus/common/model"
	"github.com/spf13/viper"
	"go.didapinche.com/foundation/plat-echo/app/ops/models"
	"go.didapinche.com/time"
	"net/url"
	"strconv"
	"strings"
)

type AlertRecordResp struct {
	ID                uint64                     `json:"id"`
	Name              string                     `json:"name"`
	State             int                        `json:"state"`
	AlertStatus       int                        `json:"alert_status"`
	CreateTime        time.Time                  `json:"create_time"`
	Message           string                     `json:"message"`
	Duration          string                     `json:"duration"`
	Value             string                     `json:"value"`
	Labels            model.LabelSet             `json:"labels"`
	Alerts            *models.Alerts             `gorm:"type:json;column:alerts" json:"alerts"`
	AlertName         string                     `gorm:"column:alert_name" json:"alert_name"`
	AlertLevel        int                        `gorm:"column:alert_level" json:"alert_level"`
	ClaimStatus       int                        `gorm:"column:claim_status" json:"claim_status"`
	ClaimUser         *models.ApplicationOwner   `gorm:"column:claim_user" json:"claim_user"`
	For               string                     `json:"for"`
	AppName           string                     `json:"app_name"`
	AlertLevelName    string                     `json:"alert_level_name"`
	Threshold         string                     `json:"threshold"`
	GraphID           uint64                     `json:"graph_id"`
	Format            models.UnitType            `json:"format"`
	Level             int                        `json:"level"`
	ApiName           string                     `json:"api_name"`
	Host              string                     `json:"host"`
	AppID             uint64                     `json:"app_id"`
	ApiID             uint64                     `json:"api_id"`
	DashboardID       uint64                     `json:"dashboard_id"`
	HostID            uint64                     `json:"host_id"`
	AppInfo           *models.Application        `json:"app_info,omitempty"`
	ApiInfo           *models.Api                `json:"api_info,omitempty"`
	HostInfo          *models.HostResource       `json:"host_info,omitempty"`
	DashboardInfo     *models.Dashboard          `json:"dashboard_info,omitempty"`
	Owners            []string                   `json:"-"`
	Owners2           []*models.ApplicationOwner `json:"owners"`
	UrlDetail         string                     `json:"url_detail"`
	UrlAlert          string                     `json:"url_alert"`
	Token             string                     `json:"token"`
	ClaimStatusString string                     `json:"claim_status_string"`
}

func GetOwners(s string) []*models.ApplicationOwner {
	if s == "" {
		return nil
	}
	var result []*models.ApplicationOwner
	err := json.Unmarshal([]byte(s), &result)
	if err != nil {
		return result
	}
	return result
}

func MakeAlertRecordResp(alert *models.AlertHistory) []*AlertRecordResp {
	alert1 := new(AlertRecordResp)
	alert2 := new(AlertRecordResp)
	alert1.Name = alert.Name
	alert1.Threshold = alert.Threshold
	alert1.Message = alert.Message
	alert1.Duration = strconv.Itoa(int(alert.Duration))
	alert1.Value = alert.Value
	alert1.AlertName = alert.AlertName
	alert2.Name = alert.Name
	alert2.Threshold = alert.Threshold
	alert2.Message = alert.Message
	alert2.Duration = strconv.Itoa(int(alert.Duration))
	alert2.AlertName = alert.AlertName
	if len((*alert.Alerts)) > 0 {
		alert1.Labels = (*alert.Alerts)[0].Labels
		alert2.Labels = (*alert.Alerts)[0].Labels
		alert1.Value = string((*alert.Alerts)[0].Annotations["value"])
		alert2.Value = string((*alert.Alerts)[0].Annotations["value"])
	}
	if len((*alert.Alerts)) > 1 {
		alert2.Labels = (*alert.Alerts)[1].Labels
		alert2.Value = string((*alert.Alerts)[1].Annotations["value"])
	}
	alert1.AppName = string(alert1.Labels["app"])
	alert1.ApiName = string(alert1.Labels["method"]) + string(alert1.Labels["uri"])
	alert2.AppName = string(alert2.Labels["app"])
	alert2.ApiName = string(alert2.Labels["method"]) + string(alert2.Labels["uri"])
	alert1.CreateTime = alert.StartTime
	alert1.State = 1
	alert1.AlertStatus = 1
	alert2.CreateTime = alert.EndTime
	alert2.State = 0
	alert2.AlertStatus = 0
	return []*AlertRecordResp{alert1, alert2}
}

func MakeAlertRecordResps(alerts2 []*models.AlertHistory) []*AlertRecordResp {
	alerts1 := make([]*AlertRecordResp, 0)
	for _, a := range alerts2 {
		alert := MakeAlertRecordResp(a)
		alerts1 = append(alerts1, alert...)
	}
	return alerts1
}

func MakeCurrentAlertRecordResps(alerts2 []*models.AlertCurrent) []*AlertRecordResp {
	alerts1 := make([]*AlertRecordResp, 0)
	for _, a := range alerts2 {
		alert := MakeCurrentAlertRecordResp(a)
		alerts1 = append(alerts1, alert)
	}
	return alerts1
}

func MakeCurrentAlertRecordResp(alert *models.AlertCurrent) *AlertRecordResp {
	alert1 := new(AlertRecordResp)
	alert1.Name = alert.Name
	alert1.ID = alert.ID
	alert1.Token = alert.Token
	alert1.Threshold = alert.Threshold
	alert1.AlertName = alert.AlertName
	alert1.Duration = time.Now().Sub(alert.StartAlertTime.Time).String()
	alert1.Alerts = alert.Alerts
	alert1.AlertLevel = alert.AlertLevel
	alert1.ClaimStatus = alert.ClaimStatus
	user := new(models.ApplicationOwner)
	err := json.Unmarshal([]byte(alert.ClaimUser), &user)
	if err == nil {
		alert1.ClaimUser = user
	}
	alert1.Owners = alert.Owners
	alert1.Owners2 = GetOwners(alert.Owner)
	alert1.AppName = alert.AppName
	alert1.Format = alert.Format
	alert1.ApiName = alert.ApiName
	if (*alert.Alerts)[0] != nil {
		if len((*alert.Alerts)) > 0 {
			alert1.Labels = (*alert.Alerts)[0].Labels
			alert1.Value = string((*alert.Alerts)[0].Annotations["value"])
			if strings.Contains(alert1.Value, ".") {
				index := strings.Index(alert1.Value, ".") + 3
				if index >= len(alert1.Value) {
					index = len(alert1.Value)
				}
				alert1.Value = alert1.Value[0:index]
			}
			(*alert1.Alerts)[0].Value = alert1.Value
			(*alert1.Alerts)[0].StartAlertTime = alert1.CreateTime
			if string((*alert.Alerts)[0].Labels[model.LabelName("hostname")]) == "" && string((*alert.Alerts)[0].Labels[model.LabelName("host")]) != "" {
				alert1.Host = string((*alert.Alerts)[0].Labels[model.LabelName("host")])
			} else if string((*alert.Alerts)[0].Labels[model.LabelName("hostname")]) != "" && string((*alert.Alerts)[0].Labels[model.LabelName("host")]) == "" {
				alert1.Host = string((*alert.Alerts)[0].Labels[model.LabelName("hostname")])
			} else if string((*alert.Alerts)[0].Labels[model.LabelName("hostname")]) != "" && string((*alert.Alerts)[0].Labels[model.LabelName("host")]) != "" {
				alert1.Host = string((*alert.Alerts)[0].Labels[model.LabelName("hostname")]) + ":" + string((*alert.Alerts)[0].Labels[model.LabelName("host")])
			} else {
				alert1.Host = ""
			}
			alert1.Message = string((*alert.Alerts)[0].Annotations["message"])
		}
	}
	alert1.AppName = string(alert1.Labels["app"])
	alert1.ApiName = string(alert1.Labels["method"]) + string(alert1.Labels["uri"])
	alert1.CreateTime = alert.StartAlertTime
	alert1.State = 1
	alert1.AlertStatus = 0
	alert1.AppID = alert.AppID
	alert1.ApiID = alert.ApiID
	alert1.DashboardID = alert.DashboardID
	alert1.HostID = alert.HostID
	alert1.Level = alert.Level
	alert1.GraphID = alert.GraphID
	if alert.ApiID != 0 {
		urlDetail := viper.GetString("alert.url")
		urlDetail += "?start_time=" + url.QueryEscape(alert.StartAlertTime.String()) + "&"
		urlDetail += "end_time=" + url.QueryEscape(time.Now().String())
		urlDetail += "&graphId=" + strconv.Itoa(int(alert.GraphID))
		urlDetail += "&time_type=custom&type=edit&sourceModule=interface"
		urlDetail += "&interfaceId=" + strconv.Itoa(int(alert.ApiID))
		alert1.UrlDetail = urlDetail
	} else {
		urlDetail := viper.GetString("alert.url")
		urlDetail += "?start_time=" + url.QueryEscape(alert.StartAlertTime.String()) + "&"
		urlDetail += "end_time=" + url.QueryEscape(time.Now().String())
		urlDetail += "&graphId=" + strconv.Itoa(int(alert.GraphID))
		urlDetail += "&time_type=custom&type=edit&sourceModule=app"
		urlDetail += "&appId=" + strconv.Itoa(int(alert.AppID)) + "&appName=" + alert.App
		alert1.UrlDetail = urlDetail
	}
	return alert1
}

func MakeAlertRecordResp2(alert *models.AlertHistory) *AlertRecordResp {
	alert1 := new(AlertRecordResp)
	alert1.Name = alert.Name
	alert1.ID = alert.ID
	alert1.Threshold = alert.Threshold
	alert1.Message = alert.Message
	alert1.Duration = alert.EndTime.Time.Sub(alert.StartTime.Time).String()
	alert1.Value = alert.Value
	alert1.Alerts = alert.Alerts
	alert1.ClaimStatus = alert.ClaimStatus
	alert1.AlertLevel = alert.AlertLevel
	alert1.AlertStatus = 1
	alert1.Owners2 = GetOwners(alert.Owner)
	user := new(models.ApplicationOwner)
	err := json.Unmarshal([]byte(alert.ClaimUser), &user)
	if err == nil {
		alert1.ClaimUser = user
	}
	alert1.AlertName = alert.AlertName
	alert1.AppID = alert.AppID
	alert1.ApiID = alert.ApiID
	alert1.HostID = alert.HostID
	alert1.DashboardID = alert.DashboardID
	alert1.GraphID = alert.GraphID
	alert1.AppID = alert.AppID
	if len((*alert.Alerts)) > 0 {
		alert1.Labels = (*alert.Alerts)[0].Labels
		alert1.Value = string((*alert.Alerts)[0].Annotations["value"])
		if strings.Contains(alert1.Value, ".") {
			index := strings.Index(alert1.Value, ".") + 3
			if index >= len(alert1.Value) {
				index = len(alert1.Value)
			}
			alert1.Value = alert1.Value[0:index]
		}
		(*alert1.Alerts)[0].StartAlertTime = alert1.CreateTime
		(*alert1.Alerts)[0].Value = alert1.Value
		*alert1.Alerts = (*alert.Alerts)[0:1]
	}

	alert1.AppName = string(alert1.Labels["app"])
	alert1.ApiName = string(alert1.Labels["method"]) + string(alert1.Labels["uri"])
	alert1.CreateTime = alert.StartTime
	alert1.State = 1
	return alert1
}

func MakeAlertRecordResps2(alerts2 []*models.AlertHistory) []*AlertRecordResp {
	alerts1 := make([]*AlertRecordResp, 0)
	for _, a := range alerts2 {
		alert := MakeAlertRecordResp2(a)
		alerts1 = append(alerts1, alert)
	}
	return alerts1
}
